#include "StdTcp.h"
#include "ClientFunc.h"
#include "StdThread.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "FileSystem.h"
#include "Clientdatacenter.h"
#include "../GlobalMessage.h"
#include <arpa/inet.h>

static char MyName[NameSize];
FileSys *fs;

bool FriendsChat = false;// 好友聊天界面标志位
bool GroupChat = false;// 群聊界面标志位


void AnalysisRecv(MSG *m)
{
    switch (m->flag)
    {
        case CHAT:
        case BROADCAST:
            printf("接收到来自|%s|的消息:%s\n",m->FromName,m->Content);
            break;
        case ONLINELIST:
        {
            ShowOnlineList(m);
            break;
        }
        case SENDFILE:
        {
            WriteToLocal(m);
            break;
        }
        case UPLOAD:
            if (strcmp(m->Content, "UPDATEOK") == 0)
            {
                printf("上传文件成功\n");
            }
            break;
        case FILELIST:
        {
            showFileList(m);
            break;
        }
        case DOWNLOAD:
        {
            static int totalSize = 0; // 文件总大小
            static int downloadedSize = 0; // 已下载的大小

            int size = 0;//读取的文件内容大小
            memcpy(&size,m->Content,4);

            if (size == -1)//下载文件完成
            {
                printf("文件下载完成\n");
                totalSize = 0; // 重置文件大小
                downloadedSize = 0; // 重置已下载大小
                break;
            }
            //打印进度条 待实现
            //
            // 获取文件总大小（假设总大小在文件名后面的8个字节）
            // if (downloadedSize == 0)
            // {
            //     memcpy(&totalSize, m->Content + 4 + NameSize, sizeof(int));
            //     totalSize = ntohl(totalSize); // 如果是网络字节序，需要转换为主机字节序
            // }

            // // 更新已下载大小
            // downloadedSize += size;

            // // 计算下载进度
            // float progress = (float)downloadedSize / totalSize * 100;

            // // 打印进度条
            // int barWidth = 50; // 进度条的宽度
            // printf("[");
            // int pos = barWidth * downloadedSize / totalSize;
            // for (int i = 0; i < barWidth; ++i)
            // {
            //     if (i < pos) printf("=");
            //     else if (i == pos) printf(">");
            //     else printf(" ");
            // }
            // printf("] %.2f%%\r", progress);
            // fflush(stdout); // 刷新输出缓冲区

            char fileName[NameSize] = {0};
            strcpy(fileName,m->Content + 4);
            WriteFileToFs(fs,NULL,fileName,m->Content + 24,size);
            break;
        }
        case ADDFRIEND:
        {
            printf("%s\n", m->Content);
            break;
        }
        case MYFRIENDLIST:
        {   
            ShowMyFriendList(m->Content);
            break;
        }
        case DELETEFRIEND:
        {
            printf("删除好友%s",m->Content);
            printf("\n");
            break;
        }
        case MYFRIENDREQUEST:// 我收到的好友请求
        {
            // 存储解析后字符串的数量
            int size = 0;
            char **ApplicationList = Splite(m->Content, ";", &size);
            for (int i = 0; i < size; i++)
            {
                printf("用户|%s|发送了好友请求\n", ApplicationList[i]);
            }
            FreeStrList(ApplicationList,size);
            break;
        }
        case CALLFRIENDREQUEST:// 回复好友请求
        {
            printf("%s\n",m->Content);
            break;
        }
        case FRIENDCHAT:// 好友聊天
        {
            if (FriendsChat == true)
            {
                if (strcmp(m->Content + 50, "该用户不存在") == 0)
                {
                    printf("该用户不存在\n");
                    DeleteMessage(m);
                    break;
                }
                else if (strcmp(m->Content+50,"该用户还未成为你的好友") == 0)
                {
                    printf("该用户还未成为你的好友");
                    DeleteMessage(m);
                    break;
                }
                MSG messages[10];// 存储聊天记录
                memset(messages,0,sizeof(messages));
                // 最多 20 条消息存储在 messages 数组中
                int count = GetMessages(messages, m->FromName, m->ToName,10);
                ShowFriendMessages(messages, MyName, count);
            }
            break;
        }
        case CREATEGROUP:
        {
            printf("%s\n",m->Content);
            break;
        }
        case VISITWHOJOINGROUP:
        {
            printf("%s\n",m->Content);
            break;
        }
        case INVITATIONJOINGROUPNOTIFICATION:
        {
            ShowGroupInvite(m);
            break;
        }
        case PROCESSGROUPINVITATION:
        {
            printf("%s\n",m->Content);
            break;
        }
        case GROUPMESSAGERECORD:
        {
            if (GroupChat == true)
            {
                if (strcmp(m->Content + 50, "您尚未加入该群组") == 0)
                {
                    printf("您尚未加入该群组\n");
                    DeleteMessage(m);
                    break;
                }
                // 存储聊天记录
                MSG messages[20];
                memset(messages,0,sizeof(messages));
                int count = GetMessagesGroup(messages,m->FromName,m->ToName,20);
                ShowGroupMessages(messages,MyName,count);
            }

            break;
        }
        case MYGROUPLIST:
        {
            ShowGroupList(m);
            break;
        }
        case DELETEGROUP:
        {
            printf("删除群%s",m->Content);
            printf("\n");
            break;
        }
        
        default:
            break;
    }
}

// 客户端读线程
void * ThreadHandle(void* arg)
{
    TcpC *c = (TcpC*)arg;
    while(1)
    {
        MSG m;
        if(TcpClientRecv(c,&m,sizeof(m)) == false)
        {
            printf("读线程接受错误!\n");
            exit(-1);
        }
        AnalysisRecv(&m);
    }
}

// 注册登录
void LoginSignUp(TcpC *c)
{
    while(1)
    {
        int choice = LoginFace();
        MSG m;
        switch (choice)
        {
        case LOGIN:
            m = Login(MyName);
            TcpClientSend(c,&m,sizeof(MSG));
            if(TcpClientRecv(c,&m,sizeof(MSG)) == false)
                exit(-1);
            if(IsLoginSuccess(&m) == true)
                return;
            break;
        case SIGNUP:
            m = SignUp(MyName);
            TcpClientSend(c,&m,sizeof(MSG));
            if(TcpClientRecv(c,&m,sizeof(MSG)) == false)
                exit(-1);
            if(IsSignUpSuccess(&m) == true)
                return;
            break;
        default:
            break;
        }
        sleep(2);
        system("clear");
    }
}

// 文件传输给服务器
void SendFileToServer(MSG *m,TcpC *c)
{
    char *fileName = GetFileNameFromPath(m->Content);// 从文件路径中获取文件名
    PackFile *pf = PacketFileInit(m->Content);// 初始化文件数据包
    
    memset(m->Content,0,sizeof(m->Content));
    strcpy(m->Content + 4,fileName);// 将文件名放入消息体中，前四个字节是存储文件大小
    int size = 1000;// 文件数据包大小
    int count = 0;
    while(IsFileEnd(pf) == false)
    {
        //从第24字节开始，读取的文件数据大小会放在size中
        ReadFromFile(pf,m->Content + 24,&size);
        //填入读取的文件内容大小
        memcpy(m->Content,&size,sizeof(int)); 
        TcpClientSend(c,m,sizeof(MSG));
        count++;//计数
        printf("msg flag : %d   这是第%d包数据,大小:%d\n", m->flag, count, size);
    }

    // 发送文件结束标志: 传结束的空包
    size = -1;
    memcpy(m->Content, &size, sizeof(int));
    TcpClientSend(c, m, sizeof(MSG));
    free(fileName);
    ClearPacketFile(pf);// 清除文件数据包资源
}

int main(int argc,char *argv[])
{
    // if(argc != 3)
    // {
    //     printf("参数数量不对\n");
    //     return -1;
    // }
    // TcpC *c = TcpClientInit(argv[1],atoi(argv[2]));
    TcpC *c = TcpClientInit("172.29.0.125", 8082);
    DataCenterInit();
    if (DataCenterInit() == false)// 数据中心初始化
    {
        printf("数据中心初始化失败\n");
        return -1;
    }
    LoginSignUp(c);// 注册或登录
    fs = FileSystemInit("./filesys");// 文件系统初始化
    
    // 创建读线程，接收到消息进行处理
    Thread *t = ThreadInit(ThreadHandle,c);
    while(1)
    {
        int choice = Interface();
        MSG m;
        switch (choice)
        {
        //私聊
        case CHAT:
            m = ChatToClient();
            strcpy(m.FromName,MyName);
            TcpClientSend(c,&m,sizeof(m));
            break;
        //广播
        case BROADCAST:
            m = ChatBroadCast();
            strcpy(m.FromName,MyName);
            TcpClientSend(c,&m,sizeof(m));
            break;
        case ONLINELIST:
            m = GetServerOnlineList();
            strcpy(m.FromName,MyName);
            TcpClientSend(c,&m,sizeof(m));
            break;
        case SENDFILE:// 发送文件
           m = SendFile();
           strcpy(m.FromName,MyName);
           SendFileToServer(&m,c);
           break;
        case MYCLOUD:
            while(1)
            {
                int choice = CloudInterface();
                switch (choice)
                {
                    case FILELIST:
                    {
                        strcpy(m.FromName, MyName);
                        m.flag = FILELIST;
                        TcpClientSend(c, &m, sizeof(m));
                        break;
                    }
                    case UPLOAD:
                    {
                        m = UpLoadFile();
                        strcpy(m.FromName,MyName);
                        SendFileToServer(&m,c);

                        break;
                    }
                    case DOWNLOAD:// //向服务器下载文件
                    {
                        m = DownLoadFile();
                        strcpy(m.FromName,MyName);
                        TcpClientSend(c,&m,sizeof(m));
                        break;
                    }
                    case RETURNTOMAINMENU:
                    {
                        break;
                    }
                    default:
                    {// 处理无效选项
                        break;
                    }
                }
                if (choice == RETURNTOMAINMENU)
                    break; // 如果选择了返回到主菜单，退出循环
            }
            break;
        case FRIENDMANAGE:
            while(1)
            {
                int choice = FriendManageInterface();
                switch (choice)
                {
                    case ADDFRIEND:// 好友添加
                    {
                        memset(&m, 0, sizeof(m));// 清空残留数据
                        m = AddNewFriend();
                        strcpy(m.FromName, MyName);
                        TcpClientSend(c, &m, sizeof(m));
                        break;
                    }
                    case MYFRIENDLIST:// 处理服务器发送的好友列表响应
                    {
                        memset(&m, 0, sizeof(m));
                        m.flag = MYFRIENDLIST;
                        strcpy(m.FromName, MyName);
                        TcpClientSend(c, &m, sizeof(m));
                        break;
                    }
                    case DELETEFRIEND:
                    {
                        memset(&m, 0, sizeof(m));
                        m = DeleteFriend();
                        strcpy(m.FromName, MyName);
                        TcpClientSend(c, &m, sizeof(m));
                        break;
                    }
                    case FRIENDCHAT:
                    {
                        FriendsChat = true;
                        memset(&m,0,sizeof(m));
                        FriendChatLoop(c,MyName);
                        FriendsChat = false;// 结束
                        break;
                    }
                    case MYFRIENDREQUEST:
                    {
                        memset(&m, 0, sizeof(m));
                        m.flag = MYFRIENDREQUEST;
                        strcpy(m.FromName, MyName);
                        TcpClientSend(c, &m, sizeof(m));
                        break;
                    }
                    case CALLFRIENDREQUEST:
                    {
                        memset(&m, 0, sizeof(m));
                        m = ResponseFriendApplication();
                        strcpy(m.FromName, MyName);
                        TcpClientSend(c, &m, sizeof(m));
                        break;
                    }
                    case FROMFRIENDMANAGETOMAINMENU:
                    {
                        break;
                    }
                    default:
                        break;
                }
                if (choice == FROMFRIENDMANAGETOMAINMENU)
                    break; // 如果选择了返回到主菜单，退出循环               
            }
            break;
        case GROUPMANAGE:
            {
                while (1)
                {
                    int choice = GroupManageInterface();

                    switch (choice)
                    {
                        case CREATEGROUP:// 创建群组
                        {
                            memset(&m,0,sizeof(m));
                            m = GroupCreate();
                            strcpy(m.FromName,MyName);
                            TcpClientSend(c,&m,sizeof(MSG));
                            break;
                        }
                        case VISITWHOJOINGROUP:
                        {
                            memset(&m,0,sizeof(m));
                            m = InviteWhoGroup();
                            strcpy(m.FromName,MyName);
                            TcpClientSend(c,&m,sizeof(MSG));
                            break;
                        }
                        case INVITATIONJOINGROUPNOTIFICATION:
                        {
                            memset(&m,0,sizeof(MSG));
                            strcpy(m.FromName,MyName);
                            m.flag =INVITATIONJOINGROUPNOTIFICATION;
                            TcpClientSend(c,&m,sizeof(MSG));
                            break;
                        }
                        case PROCESSGROUPINVITATION:
                        {
                            m = HandleInviteFunc();
                            if (m.Content[0] == 27)
                            {
                                break;
                            }
                            strcpy(m.FromName,MyName);
                            TcpClientSend(c,&m,sizeof(MSG));
                            break;
                        }
                        case GROUPMESSAGERECORD:
                        {
                            GroupChat = true;
                            memset(&m,0,sizeof(MSG));
                            char group[NameSize] = {0};
                            printf("=========================\n");
                            printf("请输入你想加入的群组:");
                            scanf("%s",group);
                            GroupChatLoop(c,MyName,group);
                            GroupChat = false;
                            break;
                        }
                        case MYGROUPLIST:
                        {
                            //查看所有的群
                            memset(&m,0,sizeof(MSG));
                            strcpy(m.FromName,MyName);
                            m.flag =MYGROUPLIST;
                            TcpClientSend(c,&m,sizeof(MSG));
                            break;
                        }
                        case DELETEGROUP:
                        {
                            memset(&m, 0, sizeof(m));
                            m = DeleteGroup();
                            strcpy(m.FromName, MyName);
                            TcpClientSend(c, &m, sizeof(m));
                            break;
                        }
                        case FROMGROUPMANAGETOMAINMENU:
                        {

                            break;
                        }
                        default:
                            break;
                    }
                    if (choice == FROMGROUPMANAGETOMAINMENU)
                        break; // 如果选择了返回到主菜单，退出循环
                }
            }
        default:
            break;
        }
    }

    return 0;
}